package com.huah.chapter3;

import java.util.Arrays;

// 迭代器模式-抽象迭代器接口
interface Iterator<T> {
    public boolean hasNext();

    public T next();
}

// 迭代器模式-抽象聚合接口
interface Aggregate<T> {
    public Iterator<T> iterator();
}


class ConcreteAggregate<T> implements Aggregate<T> {
    private final T[] items;
    private int index = 0;

    public ConcreteAggregate(T[] items) {
        this.items = items;
    }

    class ArrayIterator implements Iterator<T> {
        @Override
        public boolean hasNext() {
            return index < items.length;
        }

        @Override
        public T next() {
            if (this.hasNext()) {
                return items[index++];
            }
            return null;
        }
    }

    @Override
    public Iterator<T> iterator() {
        return new ArrayIterator();
    }
}

public class IteratorPattern {
    public static void main(String[] args) {
        String[] names = {"Huah", "James", "Lucy", "Mike"};
        Aggregate<String> aggregate = new ConcreteAggregate<>(names);
        Iterator<String> iterator = aggregate.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
